import com.game.DBHelper;
import com.game.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
    // 用户注册

    // 在原有register方法中添加用户名唯一性检查
    public boolean register(User user) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = DBHelper.getConnection();

            // 检查用户名是否存在
            String checkSql = "SELECT * FROM users WHERE username = ?";
            stmt = conn.prepareStatement(checkSql);
            stmt.setString(1, user.getUsername());
            rs = stmt.executeQuery();
            if (rs.next()) {
                return false; // 用户名已存在
            }

            // 插入新用户
            String sql = "INSERT INTO users (username, password, email) " +
                    "VALUES (?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword()); // 注意：实际应使用哈希加密
            stmt.setString(3, user.getEmail());
            return stmt.executeUpdate() > 0;
        } finally {
            DBHelper.close(conn, stmt, rs);
        }
    }

    // 更新login方法返回User对象
    public User login(String username, String password) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = DBHelper.getConnection();
            String sql = "SELECT * FROM users WHERE username=? AND password=?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setEmail(rs.getString("email"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBHelper.close(conn, stmt, rs);
        }
        return null;
    }
}